package shell

import (
	"bytes"
	"github.com/fatih/color"
	"gosh/pkg/connect"
	"gosh/pkg/handler"
	"strings"
)

func ExecuteCommand() {
	if err := initJumpServer(); err != nil {
		color.Red("init bastion failed,err:%s\n", err.Error())
		return
	}
	handler.Handler(SSHConfig.Fork, SSHConfig.Hosts, SSHConfig.PrintStatus, SSHConfig.PrintFields, execute)
}

func execute(ip string) (stdout, stderr []byte, err error) {
	host := hostMap[ip]
	jumpserver := jumpserverMap[host.BastionIP]
	// 创建ssh连接
	sshHost := connect.NewHost(ip, host.SSHUser, host.SSHPassword, host.SSHKeyContent,
		host.SSHKeyPassphrase, host.SSHPort, jumpserver, host.SSHTimeout)
	if err = sshHost.Open(); err != nil {
		return nil, nil, err
	}
	defer sshHost.Close()

	// 打开ssh会话
	client := sshHost.SSHClient
	cmd := strings.Join(SSHConfig.Args, " ")
	session, err := client.NewSession() // 开启新的ssh会话
	if err != nil {
		return nil, nil, err
	}
	defer session.Close()
	defer client.Close()

	// 指定标准输出和标准错误
	var stdOut bytes.Buffer
	var stdErr bytes.Buffer
	session.Stderr = &stdErr
	session.Stdout = &stdOut
	err = session.Run(cmd)
	return stdOut.Bytes(), stdErr.Bytes(), err

}
